package priv.mill.ws;
import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocketTest")
public class WebSocketTest {
    @OnMessage
    public void onMessage(String message, Session session) throws IOException, InterruptedException {

        // 将接收到的消息打印
        System.out.println("接收到: " + message);

        //发送第一条信息
        session.getBasicRemote().sendText("来自于服务器的消息");

        // 发送三次消息，间隔5秒
        int sentMessages = 0;
        while (sentMessages < 3) {
            Thread.sleep(5000);
            session.getBasicRemote().sendText("服务器消息. Count: " + sentMessages);
            sentMessages++;
        }

        session.getBasicRemote().sendText("服务器发送最后一个消息");
    }

    @OnOpen
    public void onOpen() {
        System.out.println("客户端连接");
    }

    @OnClose
    public void onClose() {
        System.out.println("客户端关闭");
    }
}